import {login, logout, getInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {semesterEdit} from '@/api/admin/setting'
import {systemIndex} from '@/api/admin/system'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    userInfo: null, // 用户信息
    configData: null
  },
  getters: {
    userInfo: state => state.userInfo,
    configData: state => state.configData || JSON.parse(state.configData)
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_CONFIG(state, configData) {
      state.configData = configData
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },

  actions: {
    // 登录
    Login({commit}, userInfo) {
      const account = userInfo.username.trim()
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        login(account, password).then(res => {
          // 根据系统实际情况，使用自定义token值代替可能不存在的res.token
          // 系统通过PHPSESSID维护会话，这里设置一个非空token以确保正常工作
          const dummyToken = 'session-valid';
          setToken(dummyToken)
          window.localStorage.setItem('userRole', res.data?.power || '')
          commit('SET_TOKEN', dummyToken)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          console.log('用户信息：', res)
          const user = res.detail
          const avatar = (user.pic == "" || user.pic == null) ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.pic;
          window.localStorage.setItem('userDoc', JSON.stringify(user))
          if (user.role && user.role.length > 0) { // 验证返回的roles是否是一个非空数组
            // commit('SET_ROLES', res.roles)
            // commit('SET_PERMISSIONS', res.permissions)
            // commit('SET_USERINFO', user)

            console.log('有权限')
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }

          commit('SET_NAME', user.realname)
          commit('SET_AVATAR', avatar)
          commit('SET_USERINFO', user)
          this.dispatch('getSetting')
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          window.localStorage.removeItem('userDoc')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    // 当前学期
    getSemester() {
      return new Promise((resolve, reject) => {
        semesterEdit().then(res => {
          console.log('getSemester学期：', res)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 系统设置
    getSetting({commit, state}) {
      return new Promise((resolve, reject) => {
        systemIndex().then(res => {
          console.log('设置全局的变量-系统设置', res)
          commit('SET_CONFIG', res.vo)
          resolve(res)
        }).catch(e => {
          reject(e)
        })
      })
    },
  }
}

export default user
